package com.blb.day19_shiro.demo;

import com.blb.day19_shiro.realm.MyRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

public class Demo1 {

    public static void main(String[] args) {
        //创建安全管理器
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //设置Realm对象
        MyRealm realm = new MyRealm();
        //创建密码匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher("md5");
        //设置迭代次数
        credentialsMatcher.setHashIterations(10);
        //给Realm设置密码匹配器
        realm.setCredentialsMatcher(credentialsMatcher);
        securityManager.setRealm(realm);
        //给SecurityUtils设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        //获得Subject对象
        Subject subject = SecurityUtils.getSubject();
        //登录
        UsernamePasswordToken token = new UsernamePasswordToken("user-1", "123");
        try {
            subject.login(token);
            System.out.println("登录成功！");
            //判断是否具有管理员角色
            if(subject.hasRole("admin")){
                System.out.println("是管理员，可以执行");
            }
            //是否具有某个权限
            if(subject.isPermitted("user:list")){
                System.out.println("可以查询用户");
            }
        }catch (UnknownAccountException ex){
            ex.printStackTrace();
            System.out.println("登录失败，用户名不存在");
        }catch (IncorrectCredentialsException ex){
            ex.printStackTrace();
            System.out.println("登录失败，密码错误");
        }catch (AuthenticationException ex){
            ex.printStackTrace();
            System.out.println("登录失败");
        }
    }
}
